package com.yifi.system.service;

import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import cn.hutool.core.util.StrUtil;

public class MisOrgService {

	public List<Record> getTree(List<Record> plist,String c_pro)
	{
		return getTree("id","name",plist,c_pro);
	}
	public List<Record> getTree(String cvalue,String ctext,List<Record> plist,String c_pro)
	{
		String sql="select ccode as "+cvalue+",cname as "+ctext+",ilayer from mis_org where ilayer='1' ";
		if(StrUtil.isNotEmpty(c_pro))
		{
			sql+=" and c_pro='"+c_pro+"'";
		}
		List<Record> list=Db.find(sql);
		if(plist!=null)
		{
			for (Record r : plist) {
				String ccode=r.getStr(cvalue);
				int ilayer=Integer.parseInt(r.getStr("ilayer"))+1;
				sql="select ccode as "+cvalue+",cname as "+ctext+",ilayer from mis_org where ccode like '"+ccode+"%' and ilayer='"+ilayer+"'";
				if(StrUtil.isNotEmpty(c_pro))
				{
					sql+=" and c_pro='"+c_pro+"'";
				}
				List<Record> clist=Db.find(sql);
				if(clist.size()>0)
				{
					r.set("open", true);
					r.set("children", getTree(cvalue,ctext,clist,c_pro));
				}
			}
			
			return plist;
		}
		else
		{
			return getTree(cvalue,ctext,list,c_pro);
		}
	}
	
	public List<Record> getTree(String cvalue,String ctext,List<Record> plist,String bmclass,String c_pro)
	{
		String sql="select ccode as "+cvalue+",cname as "+ctext+",ilayer from mis_org where ilayer='1'";
		if(StrUtil.isNotEmpty(c_pro))
		{
			sql+=" and c_pro='"+c_pro+"'";
		}
		List<Record> list=Db.find(sql);
		if(plist!=null)
		{
			for (Record r : plist) {
				String ccode=r.getStr(cvalue);
				int ilayer=Integer.parseInt(r.getStr("ilayer"))+1;
				sql="select ccode as "+cvalue+",cname as "+ctext+",ilayer from mis_org where ccode like '"+ccode+"%' and ilayer='"+ilayer+"'";
				if(StrUtil.isNotEmpty(c_pro))
				{
					sql+=" and c_pro='"+c_pro+"'";
				}
				
				
				List<Record> clist=Db.find(sql);
				if(clist.size()>0)
				{
					r.set("open", true);
					r.set("children", getTree(cvalue,ctext,clist,c_pro));
				}
			}
			
			return plist;
		}
		else
		{
			return getTree(cvalue,ctext,list,"",c_pro);
		}
	}

	public List<Record> getTreeIdPid(String cvalue,String ctext,List<Record> plist)
	{
		String sql="select ccode as "+cvalue+",cname as "+ctext+",ilayer,'00' as pid from mis_org where ilayer='1'";
		List<Record> list=Db.find(sql);
		if(plist!=null)
		{
			for (Record r : plist) {
				String ccode=r.getStr(cvalue);
				int ilayer=Integer.parseInt(r.getStr("ilayer"))+1;
				sql="select ccode as "+cvalue+",cname as "+ctext+",ilayer,'"+ccode+"' as pid from mis_org where ccode like '"+ccode+"%' and ilayer='"+ilayer+"'";
				List<Record> clist=Db.find(sql);
				/*
				if(clist.size()>0)
				{
					r.set("open", true);
					r.set("children", getTreeIdPid(cvalue,ctext,clist));
				}
				*/
			}
			
			return plist;
		}
		else
		{
			return getTreeIdPid(cvalue,ctext,list);
		}
	}
}
